//实现Account表的增删改查

const Accounts = require('../models/Accounts')
const { hash, compare } = require('../utils/hash')
//增加记录
//account(name, password, juri)
async function createAccount({ name, password, juri = 0 }) {
  //查询是否存在该用户
  let result = await queryByName(name)
  if (result.msg === '查询成功') {
    return {
      msg: '该用户已注册了,请更换用户名',
      status: 0,
    }
  } else {
    let result = await Accounts.create({
      name,
      password, // Accounts.js 的 set 钩子会自动加密
      juri: typeof juri === 'number' ? juri : 0,
    })
    return {
      msg: '注册成功',
      status: 1,
      data: result.toJSON(),
    }
  }
}

//删除记录(以获取id删除)
async function deleteAccount(id) {
  let result = await queryAccount({
    id,
  })
  if (result.length > 0) {
    await result[0].destroy()
    return {
      msg: '删除成功',
    }
  } else {
    return {
      msg: '未找到该用户',
    }
  }
}

//更新记录(获取id更新)
async function updateAccount(id, account) {
  let result = await queryAccount({ id })
  if (result.length > 0) {
    if (account.name) result[0].name = account.name
    if (account.password) result[0].password = account.password // set 钩子自动加密
    if (typeof account.juri === 'number') result[0].juri = account.juri
    await result[0].save()
    return {
      msg: '更新成功',
    }
  } else {
    return {
      msg: '未找到该用户',
    }
  }
}

//查询记录
async function queryAccount(where) {
  let result = await Accounts.findAll({
    where,
  })
  return result
}

//根据姓名查询
async function queryByName(name) {
  // let where = { name };
  // let result = await Accounts.findOne(where);
  let result = await Accounts.findOne({
    where: {
      name,
    },
  })
  if (result) {
    return {
      msg: '查询成功',
      data: result,
    }
  } else {
    return {
      msg: '未找到该用户',
    }
  }
}

//根据用户名和密码查询用户
const findAccount = async ({ name, password }) => {
  let result = await queryByName(name)
  if (result.msg === '未找到该用户') {
    return {
      msg: '用户不存在',
      status: 0,
    }
  } else {
    let account = result.data
    let { name: dbname, password: dbpassword, juri, id } = account
    if (dbname === name && compare(password, dbpassword)) {
      // 生成 token（如有 token 逻辑可补充）
      return {
        msg: '登录成功',
        status: 1,
        juri, // 0: 普通用户, 1: 交管部门, 2: 管理员
        user: { id, name, juri },
        // token: 'xxx',
      }
    } else {
      return {
        msg: '密码错误',
        status: 0,
      }
    }
  }
}
module.exports = {
  createAccount,
  queryAccount,
  deleteAccount,
  updateAccount,
  queryByName,
  findAccount,
}
